<script type="text/javascript" src="/theme/default/assets/public.js"></script>
<style>
  * {
    margin: 0;
    padding: 0;
  }
</style>
<div id="paypal-button-container" style="width: 100%;"></div>
<script>
  (function () {
    var cart_param = "";
    function askParentToValidate(ec_action_from) {
      return new Promise(resolve => {
        function handler(e) {
          if (e.data.type === 'GET_PRODUCT_INFO_RESULT') {
            window.removeEventListener('message', handler);
            console.log('e.data.ret', e.data.ret);
            if (e.data.ret.code === 0) {
              cart_param = e.data.ret.data;
              resolve(true);
            } else {
              resolve(false);
            }
          }
        }
        window.addEventListener('message', handler);
        window.parent.postMessage({ type: 'GET_PRODUCT_INFO', ec_action_from }, '*');
      });
    }
    function paypalInit({ config, payment_id, ec_action_from, currency, pay_id }) {
      var paypal_redirect_url = '';
      paypal.Buttons({
        style: {
          layout: 'horizontal',
        },
        onClick: async function (data, actions) {
          return await askParentToValidate(ec_action_from);
        },
        createOrder: function (data, actions) {
          window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: true, pay_id: pay_id } }, '*');
          return fetch('/checkouts-paypal/restapi-VY2P5BTB/ecinlinepay', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              payment_id,
              cart_param,
              currency,
              local_token: config.local_token,
            })
          }).then(function (res) {
            return res.json();
          }).then(function (data) {
            if (data.code == 0) {
              paypal_redirect_url = data.data.return_url;
              return data.data.paypal_order_id;
            }
            else {
              alert(data.data.L_LONGMESSAGE0 || data.data.msg);
              window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
              return false;
            }
          }).catch(function (err) {
            window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
            return false;
          });
        },
        onCancel: function (data) {
          window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
        },
        onError: function (data) {
          window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
        },
        onApprove: function (data, actions) {
          if (paypal_redirect_url != '') {
            window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
            top.location.href = paypal_redirect_url;
            return;
          }
          return actions.redirect();
          return fetch('/my-server/capture-order/' + data.orderID, {
            method: 'POST'
          }).then(function (res) {
            if (!res.ok) {
              window.parent.postMessage({ type: 'shop_iframeResize', data: { fullscreen: false, pay_id: pay_id } }, '*');
              alert('Something went wrong');
            }
          });
        }
      }).render('#paypal-button-container');
    }
    window.addEventListener('message', function (event) {
      if (event.data.type === 'init') {
        var messageData = event.data.data;
        var { config, currency, client_id } = messageData;
        var url = "https://www.paypal.com/sdk/js"
        var params = {
          "client-id": client_id,
          currency: currency,
          components: "buttons,messages",
          commit: "false",
        }
        if (config.payment_mode == 'authorize') {
          params["intent"] = "authorize";
        }
        const paypalURL = url + "?" + new URLSearchParams(params).toString();
        moi.createScript(paypalURL, function () {
          if (window.paypal) {
            paypalInit(messageData)
          } else {
            const timer = setInterval(() => {
              if (window.paypal) {
                paypalInit(messageData)
                clearInterval(timer)
              }
            }, 200)
          }
        })
      }
    });

  })()
</script>